require 'unicode'

class String
  
  def truncate(length = 30, truncate_string = '...')
    l = length - truncate_string.chars.length
    self.chars.length > length ? self.chars[0...l] + truncate_string : self
  end
  
  
  STOPWORDS = [
    'de','a','que','no','tiene','en','para',
    'por','le','la','lo','las','los','el',
    'una','un'
  ]
  
  def to_slug( length = 64, drop_stopwords = false )
    return "" if self.length == 0
    
    str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'').downcase
    
    # stopwords
    if drop_stopwords
      STOPWORDS.each do |stopword|
        str.gsub!( /\s#{stopword}\s|^#{stopword}\s/, ' ' )
      end
    end
    
    str = str.gsub(/[^A-Za-z0-9]/, '-').gsub(/^-+/,'').gsub(/-+$/,'').downcase
    str = str[0..length-1]
  end

end
